﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using System.Data;
using CardLogistics.Model.Ordering;
using CardLogistics.Model.Approval;
using CardLogistics.Model.CardArrival;
using System.Text;
using System.IO;
using System.Data.OleDb;

namespace CardLogistics.Web.MainPage.CardArrival.StorageCheck
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.CardArrival.Storage_Check_CardData DAL = new DAL.CardArrival.Storage_Check_CardData();
        private static readonly CardLogistics.DAL.CardArrival.Storage_Detailed_CardData DetailedDAL = new CardLogistics.DAL.CardArrival.Storage_Detailed_CardData();
        private static readonly CardLogistics.DAL.Ordering.Ordering_DetailedData OrderDAL = new CardLogistics.DAL.Ordering.Ordering_DetailedData();
        private static readonly DAL.CardRecordData cardRecordDal = new CardLogistics.DAL.CardRecordData();
        string FileValue = ""; //验收入库明细字段
        /// <summary>
        /// 增加的行
        /// </summary>
        protected StringBuilder AddTr = new StringBuilder();

        public static string TitleName;

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                STORAGEDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//入库日期
                EXAMINER.Value = LoggedUser.USERFULLNAME;//卡片验收员默认为当前登录用户
                BindDLL(ddlStorageType, "basic_basictype", "typename", "id", " and typeno=2 and  status<>1 and isdelete=0");//入库类型
                InitControl();
            }
        }
        #endregion

        #region 得到一个对象实体
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public void InitControl()
        {
            TitleName = GetStatusInfo(0, "卡片验收货入库");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    Storage_Check_Card sData = DAL.GetModel(_key);
                    SetWebControls(this.Page, sData);
                    hf_OrderId.Value = sData.ORDERID;//订单ID
                    DataTable dd = OrderDAL.GetInfoById(sData.ORDERID);//通过订单外键得到订单信息
                    if (dd.Rows.Count > 0)
                    {
                        OrderNumber.Value = Convert.ToInt32(dd.Compute("sum(FORMATNUMBER)", "")).ToString();//订单总数量
                    }
                    ddlStorageType.SelectedValue = sData.STORAGETYPE; //入库类型

                    //根据验收入库外键查询入库明细
                    DataTable dt = DetailedDAL.GetInfoByCheckId(_key);
                    string detId = "";
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        //获取编辑前的卡片数量
                        hfEditSumCard.Value = dt.Compute("sum(actualnumber)", "").ToString();
                        foreach (DataRow dr in dt.Rows)
                        {
                            detId += dr["boxno"].ToString() + "|" + dr["cardno"].ToString() + "|" + dr["startno"].ToString() + "|" + dr["endno"].ToString() + "|" +
                                     dr["DeservedNumber"].ToString() + "|" + dr["actualnumber"].ToString() + "|" + dr["missingcardno"].ToString() + ";";
                        }
                        AddRows(dt);//动态添加行
                        
                        hf_CheckId.Value = detId.TrimEnd(';');
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (sData.IsSubmit == 0 || sData.IsSubmit == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    TitleName = GetStatusInfo(sData.IsSubmit, "卡片验收货入库");

                    //通过订单ID得到订单总数量和已入库的总数量
                    DataTable orderdt = CardLogistics.DAL.CommonData.GetList("*", "v_ordering_cardinfo", "ID='" + sData.ORDERID + "'");
                    OrderNumber.Value = orderdt.Rows[0]["CardTotal"].ToString(); //订单总数量
                    putInTotal.Value = orderdt.Rows[0]["PutInTotal"].ToString();//已入库数量
                }
            }
            else
            {
                hfEditSumCard.Value ="0";
                CHECKNO.Value = GetBillNumber("卡片验收入库");
            }
        }
        #endregion

        #region 保存事件
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 保存并提交
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);

            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(3, result.Split(',')[1]); //3:卡片验收入库
                    InsertLog("保存并提交卡片验收入库信息,入库单号:" + CHECKNO.Value);
                }
                else
                    InsertLog("保存卡片验收入库信息,入库单号:" + CHECKNO.Value);
                ReturnListInfo();
            }
            else if (result.Split(',')[0] == "-1")
            {
                //判断入库明细中起始卡号和结束卡号是否重复
                ShowMessageBox(result.Split(',')[1]);
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        #region 得到对象
        /// <summary>
        /// 卡片验收入库信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            Storage_Check_Card model = new Storage_Check_Card();
            model = GetWebControls<Storage_Check_Card>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;//最后修改人
            model.LASTUPDATEDATE = DateTime.Now; //最后修改时间
            model.STORAGETYPE = ddlStorageType.SelectedValue; //入库类型
            model.ORDERID = hf_OrderId.Value;//订单ID
            model.DUENUMBER = Convert.ToInt32(OrderNumber.Value);//订单数量
            model.IsSubmit = issubmit;//0 未提交 1 待审核 2 审核中 3 驳回 4 审核不通过 5审核通过

            FileValue = hf_CheckId.Value; //验收入库明细字段

            bool isStorage = false;//是否是二次利用入库和缺卡入库
            if (ddlStorageType.SelectedValue == "5DDA8F0A65AE4BDDA21A622EA6E1F257" || ddlStorageType.SelectedItem.Text == "二次利用入库"
                || ddlStorageType.SelectedValue == "AC537E666ADC46199AA742AAA5D43B2E" || ddlStorageType.SelectedItem.Text == "缺卡入库")
            {
                isStorage = true;
            }
            #region 判断验收入库明细数据是否符合标准
            //入库类型是“二次利用入库”时，不用选择订单，且不用验证入库明细是否重复(5DDA8F0A65AE4BDDA21A622EA6E1F257是二次利用入库的ID值)
            if (FileValue != "" && !isStorage)
            {
                string[] detail = FileValue.Split(';');
                string message = "";//提示信息
                string boxNo = ""; //箱号
                string startNo = ""; //起始卡号
                string endNo = ""; //结束卡号
                int dueSum = 0;//　应有数量
                int actualNum = 0; //应有数量
                string missCardNo = ""; //缺失卡号
                string[] BoxCardNo = new string[detail.Length];//保存明细中的箱号盒号
                string[] StartCardNo = new string[detail.Length];//保存明细中的开始卡号
                //判断入库明细中起始卡号和结束卡号是否已存在
                for (int i = 0; i < detail.Length; i++)
                {
                    boxNo = detail[i].Split('|')[0].Trim();//箱号
                    startNo = detail[i].Split('|')[2].Trim().Replace("'","");//起始卡号
                    endNo = detail[i].Split('|')[3].Trim().Replace("'","");//结束卡号
                    dueSum = Convert.ToInt32(detail[i].Split('|')[4].Trim());//应有数量
                    actualNum = Convert.ToInt32(detail[i].Split('|')[5].Trim());//实际数量
                    missCardNo = detail[i].Split('|')[6].Trim().Trim(); //缺失卡号
                    string index = "第" + (i + 1) + "行";//提示明细行号
                    string strRuKuID = "";//卡片验收入库ID
                    if (IsEdit)
                    {
                        strRuKuID = Request.QueryString["Id"].ToString();
                    }
                    #region 判断明细中盒号是否重复
                    bool isExit = false;
                    string strCardNO = detail[i].Split('|')[1].Trim();//盒号
                    //判断明细中盒号是否录入重复
                    if (BoxCardNo != null)
                    {
                        isExit = BoxCardNo.Contains(strCardNO);
                        if (isExit)
                        {
                            message += index + "盒号录入重复！\n";
                        }
                    }
                    if (!isExit)
                    {
                        BoxCardNo[i] = strCardNO;
                    }
                    // 根据盒号判断是否在卡片验收入库单中已存在
                    string strResult = cardRecordDal.IsExisBoxCardNORuKu(strRuKuID, boxNo, strCardNO);
                    if (strResult != "")
                    {
                        message += index + strResult + "在库中已存在！\n";
                    }
                    #endregion

                    #region 根据订单ID、明细中的箱号、开始卡号、结束卡号判断验收入库单明细是否符合卡片订货单标准
                    bool isInOrder = cardRecordDal.IsInOrderInfoExisBoxCardNO(hf_OrderId.Value, boxNo, startNo, endNo);
                    if (!isInOrder)
                        message += index + "箱号或卡号范围不符合该订货单标准！\n";
                    #endregion

                    #region 判断卡号是否重复
                    bool isCard = false;
                    //判断明细中开始卡号是否录入重复
                   if (StartCardNo != null)
                    {
                        isCard = StartCardNo.Contains(startNo);
                        if (isCard)
                        {
                            message += index + "卡号录入重复！\n";
                        }
                    }
                   if (!isCard)
                   {
                       StartCardNo[i] = startNo;
                   }
                    #endregion

                    #region 根据开始卡号、结束卡号判断是否在卡片验收入库单中已存在

                    bool IsExisRuKu = cardRecordDal.IsExisRuKu(strRuKuID, startNo, endNo);
                    if (IsExisRuKu)
                    {
                        message += index + "卡号范围在库中已存在！\n";
                    }
                    #endregion

                    #region 循环判断每一个缺卡卡号长度是否为8位数字，并且在开始卡号和结束卡号之间；如果缺卡卡号为空，且实际数量小于等于应有数量时，则提示未录入缺卡卡号
                    if (missCardNo == "''")//缺卡卡号为空
                    {
                        if (actualNum < dueSum)//实际数量小于等于应有数量
                        {
                            message += index + "未录入缺卡卡号！\n";
                        }
                    }
                    else
                    {
                        //循环判断每一个缺卡卡号长度是否为8位数字，并且在开始卡号和结束卡号之间
                        string[] misNos = missCardNo.Split(',');//单个缺卡卡号
                        for (int j = 0; j < misNos.Length; j++)
                        {
                            string tempMis = misNos[j].Trim().Replace("'", "");
                            if (tempMis.Length != 8)//判断每一个缺卡卡号长度是否为8位数字
                            {
                                message += index + "缺卡卡号‘" + tempMis + "’位数输入有误！\n";
                            }
                            else
                            {
                                //判断缺卡卡号是否在开始卡号和结束卡号之间
                                if (int.Parse(tempMis) < int.Parse(startNo) || int.Parse(tempMis) > int.Parse(endNo))
                                {
                                    message += index + "缺卡卡号‘" + tempMis + "’已超出卡号范围！\n";
                                }
                            }
                        }
                    }
                    #endregion

                    #region 缺卡卡号有值时判断实际数量
                    if (missCardNo != "''")
                    {
                        int missNumber = missCardNo.Split(',').Length;//缺失卡号数量
                        int actualNumber = dueSum - missNumber;//实际数量=应有数量-缺失卡号数量
                        if (dueSum == actualNum || actualNum != actualNumber)
                        {
                            message += index + strResult + "实际数量输入有误！\n";
                        }
                    }
                    #endregion
                }
                if (message != "")
                {
                    return "-1," + message;
                }
            }
            #endregion

            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model, FileValue);
            }
            else
            {
                result = DAL.Add(model, FileValue);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("卡片验收入库");
                }
            }
            return result;
        }
        #endregion

        #region 卡片验收入库导入
        /// <summary>
        /// 卡片验收入库导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //static object basePath = "~/MainPage/File/CheckUpFile/"; //读取Excel的路径
        protected void btnImport_Click(object sender, EventArgs e)
        {
            string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//获得文件的扩展名
            if (IsXls != ".xls" && IsXls != ".xlsx")
            {
                ShowMessageBox("只可以选择Excel文件");
                return;
            }
            HttpPostedFile file = this.FileUpload1.PostedFile;

            string filename = FileUpload1.FileName;//获取Execle文件名
            string filePath = Server.MapPath("~/MainPage/File/CheckUpFile/" + FileUpload1.FileName);
            file.SaveAs(filePath);
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"));
            try
            {
                //第一种方法：传统方法，采用OleDB读取EXCEL文件 
                //优点：写法简单，缺点：服务器必须安有此组件才能用，不推荐使用

                //DataSet ds = GetDataFromExcel(filePath, filename);  //调用自定义方法
                //DataTable dt = ds.Tables[0];

                //第二种方法：用第三方组件：NPOI组件,推荐使用此方法
                //DataTable dt = ReadExcel(basePath, filename);
                DataTable dt = ExcelHelper.GetDataTable(filePath);

                //循环移除DataTable中的空行
                List<DataRow> removelist = new List<DataRow>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    bool rowIsNull = true; //标记是否有空行
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                        {

                            rowIsNull = false;
                        }
                    }
                    if (rowIsNull)
                    {
                        removelist.Add(dt.Rows[i]);
                    }
                }
                for (int i = 0; i < removelist.Count; i++)
                {
                    dt.Rows.Remove(removelist[i]);
                }

                string detId = "";
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        detId += dr["箱号"].ToString() + "|" + dr["盒号"].ToString() + "|" + dr["起始卡号"].ToString() + "|" + dr["结束卡号"].ToString() + "|" +
                                 dr["应有数量/张"].ToString() + "|" + dr["实际数量/张"].ToString() + "|" + dr["缺卡卡号"].ToString() + ";";

                    }
                    AddRows(dt);//动态添加行
                    hf_CheckId.Value = detId.TrimEnd(';');
                }
            }
            catch
            { }
            finally
            {
                fs.Flush(); //释放流
                fs.Close();//关闭流
            }
        }
        #endregion

        #region 模板下载
        /// <summary>
        /// 模板下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            string excelFile = Server.MapPath("~/MainPage/File/DownLoad/白卡入库导入模板.xls");
            DownLoad(excelFile, "白卡入库导入模板.xls");
        }
        #endregion

        #region
        /// <summary>
        /// 动态添加行
        /// </summary>
        /// <param name="dt"></param>
        private void AddRows(DataTable dt)
        {
            //动态创建行
            for (int i = 11; i <= dt.Rows.Count; i++)
            {
                AddTr.Append("<tr><td align='center' width='70px'>" + i + "</td>");
                AddTr.Append("<td><input name='BoxNo' type='text' class='dfinput' onkeydown='onlyNumCode();' maxlength='11'/></td>");
                AddTr.Append("<td><input name='CardNo' type='text' class='dfinput' onkeydown='onlyNumCode();' maxlength='11'/></td>");
                AddTr.Append("<td><input name='StartNo' type='text' class='dfinput' onkeydown='onlyNum();' maxlength='8'/> </td>");
                AddTr.Append("<td><input name='EndNo' type='text' class='dfinput' onkeydown='onlyNum();' maxlength='8'/></td>");
                AddTr.Append("<td><input name='DeservedNumber' type='text' class='dfinput' value='0' onkeydown='onlyNum();' maxlength='9'/></td>");
                AddTr.Append("<td><input name='ActualNumber' type='text' class='dfinput' value='0' onkeydown='onlyNum();' maxlength='9'/></td>");
                AddTr.Append("<td><input name='MissingCardNo' type='text' class='dfinput' /></td>");
                AddTr.Append("<td>&nbsp;</td></tr>");
            }
        }
        #endregion
    }
}